package com.demo.demo4j;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;

/**
 * 写入xml dom4j 操作
 */
public class HrWriter {

    public static void main(String[] args) {

        Write();
    }

    public static void Write() {
        String file="E:\\DemoStudy\\Java\\2020\\12\\2020webDemoAll\\xmlDemo\\src\\main\\java\\xml\\hr.xml";
        //SAXReader类是读取XML文件的核心类，用于将XML解析后以“树”的形式保存在内存中。
        SAXReader reader = new SAXReader();
        try {
            //从底部继续写
            Document document = reader.read(file);
            Element root = document.getRootElement();
            Element employee = root.addElement("employee");
            employee.addAttribute("no", "3311");
            Element name = employee.addElement("name");
            name.setText("李铁柱2233");
            employee.addElement("age").setText("37");
            employee.addElement("salary").setText("3600");
            Element department = employee.addElement("department");
            department.addElement("dname").setText("人事部");
            department.addElement("address").setText("XX大厦-B105");

            //以上是将数据写入到内存，还没有写入到xml文档
            Writer writer = new OutputStreamWriter(new FileOutputStream(file) , "UTF-8");
            document.write(writer);
            writer.close();

            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
